import { NextRequest, NextResponse } from 'next/server'
import { mysql, redis } from '@/utils/db'

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const page = parseInt(searchParams.get('page') || '1', 10)
    const pageSize = parseInt(searchParams.get('pageSize') || '20', 10)

    const skip = (page - 1) * pageSize
    const take = pageSize

    const total = await mysql.gpt_chat_history.count()
    const gpt_list = await mysql.gpt_chat_history.findMany({
      orderBy: {
        created_at: 'desc',
      },
      skip,
      take,
    })

    const data = gpt_list.reverse()

    // Redis 存储最近 10 条记录（第一页才设置）
    if (page === 1) {
      const recent = data.slice(-10).map((item) => ({
        role: item.sender_type === 'user' ? 'user' : 'system',
        content: item.message,
      }))
      await redis.set('user_1_chatHistory', JSON.stringify(recent))
      await redis.expire('user_1_chatHistory', 60 * 60 * 24)
    }

    return NextResponse.json(
      {
        data,
        meta: {
          total,
          page,
          pageSize,
          totalPages: Math.ceil(total / pageSize),
        },
      },
      { status: 200 }
    )
  } catch (error) {
    return NextResponse.json(
      {
        error: 'Failed to fetch chat history',
        details: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    )
  }
}
